package cn.hackcloud.concurrency.per.chat;

import java.io.*;
import java.net.Socket;
/**
* 客户端
* Created by www.hackcloud.cn
*/
public class ClientHandler implements Runnable {
    private final Socket socket;
    private final String clientIdentify;

    public ClientHandler(final Socket socket) {
        this.socket = socket;
        this.clientIdentify = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
    }

    @Override
    public void run() {
        try {
            this.chat();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void chat() throws IOException {
        BufferedReader bufferedReader = wrap2Reader(this.socket.
                getInputStream());
        PrintStream printStream = wrap2Print(this.socket.getOutputStream());
        String received;
        while ((received = bufferedReader.readLine()) != null) {
            //将客户端发送的消息输出到控制台
            System.out.printf("client: 8s-message :8s\n", clientIdentify, received);
            if (received.equals("quit")) {
                //1如果客户端发送了quit指令，则断开与客户端的连接
                write2Client(printStream, "client will close");
                socket.close();
                break;
            }
            //向客户端发送消息
            write2Client(printStream, "Server:" + received);
        }

    }

    //将输入字节流封装成BufferedReader缓冲字符流
    private BufferedReader wrap2Reader(InputStream inputStream) {
        return new BufferedReader(new InputStreamReader(inputStream));
    }
    //将输出字节流封装成PrintStream

    private PrintStream wrap2Print(OutputStream outputStream) {
        return new PrintStream(outputStream);
    }

    //该方法主要用于向客户端发送消息
    private void write2Client(PrintStream print, String message) {
        print.println(message);
        print.flush();

    }

    public static void main(String[] args) throws Exception {
        new ChatServer().startServer();
    }
}
